import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { moduleApi } from '@/api/modules'
import { useAppStore } from './app'

export const useModulesStore = defineStore('modules', () => {
  // 状态
  const modules = ref([])
  const currentModule = ref(null)
  const loading = ref(false)
  const total = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(20)
  const filters = ref({
    search: '',
    type: '',
    component: '',
    sortBy: 'name',
    sortOrder: 'asc'
  })

  // 计算属性
  const filteredModules = computed(() => {
    let result = [...modules.value]

    // 搜索过滤
    if (filters.value.search) {
      const search = filters.value.search.toLowerCase()
      result = result.filter(module => {
        const name = module.name || (Array.isArray(module) ? module[4] : '') || ''
        const subsystem = module.subsystem || (Array.isArray(module) ? module[2] : '') || ''
        const componentName = module.componentName || (Array.isArray(module) ? module[3] : '') || ''

        return name.toLowerCase().includes(search) ||
               subsystem.toLowerCase().includes(search) ||
               componentName.toLowerCase().includes(search)
      })
    }

    // 类型过滤
    if (filters.value.type) {
      result = result.filter(module => {
        const type = module.type || (Array.isArray(module) ? module[1] : '') || ''
        return type === filters.value.type
      })
    }

    // 部件过滤
    if (filters.value.component) {
      result = result.filter(module => {
        const componentName = module.componentName || (Array.isArray(module) ? module[3] : '') || ''
        return componentName === filters.value.component
      })
    }

    // 排序
    result.sort((a, b) => {
      let aValue, bValue

      // Handle both object and array formats
      if (filters.value.sortBy === 'name') {
        aValue = a.name || (Array.isArray(a) ? a[4] : '') || ''
        bValue = b.name || (Array.isArray(b) ? b[4] : '') || ''
      } else if (filters.value.sortBy === 'componentName') {
        aValue = a.componentName || (Array.isArray(a) ? a[3] : '') || ''
        bValue = b.componentName || (Array.isArray(b) ? b[3] : '') || ''
      } else if (filters.value.sortBy === 'subsystem') {
        aValue = a.subsystem || (Array.isArray(a) ? a[2] : '') || ''
        bValue = b.subsystem || (Array.isArray(b) ? b[2] : '') || ''
      } else {
        aValue = a[filters.value.sortBy] || ''
        bValue = b[filters.value.sortBy] || ''
      }

      if (filters.value.sortOrder === 'desc') {
        return bValue > aValue ? 1 : -1
      } else {
        return aValue > bValue ? 1 : -1
      }
    })

    return result
  })

  const paginatedModules = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return filteredModules.value.slice(start, end)
  })

  const moduleStats = computed(() => {
    const stats = {
      total: modules.value.length,
      types: {},
      components: {},
      dependencies: {
        direct: 0,
        indirect: 0,
        total: 0
      },
      symbols: {
        provided: 0,
        undefined: 0,
        matched: 0,
        unmatched: 0
      }
    }

    modules.value.forEach(module => {
      // 统计模块类型
      stats.types[module.type] = (stats.types[module.type] || 0) + 1

      // 统计部件
      stats.components[module.component] = (stats.components[module.component] || 0) + 1

      // 统计依赖
      stats.dependencies.direct += (module.deps_count || 0)
      stats.dependencies.indirect += (module.deps_indirect_count || 0)
      stats.dependencies.total += (module.deps_total_count || 0)

      // 统计符号
      stats.symbols.provided += (module.provided_count || 0)
      stats.symbols.undefined += (module.undefined_count || 0)
      stats.symbols.matched += (module.matched_undefined_count || 0)
      stats.symbols.unmatched += (module.unmatched_undefined_count || 0)
    })

    return stats
  })

  // 方法
  const fetchModules = async () => {
    loading.value = true
    try {
      const appStore = useAppStore()
      const productName = appStore.currentProduct
      const version = appStore.currentVersion

      if (!productName) {
        throw new Error('请先选择产品')
      }

      if (!version) {
        throw new Error('请先选择产品版本')
      }

      console.log('Fetching modules for:', productName, version)

      const response = await moduleApi.getModules(productName, version)

      if (!response || !response.data) {
        console.warn('No modules data received')
        modules.value = []
        total.value = 0
        return
      }

      // Transform array data to objects
      // Handle both wrapped response format { data: [...] } and direct array format
      let rawData = response.data || []

      if (rawData && typeof rawData === 'object' && Array.isArray(rawData.data)) {
        // Response format: { "data": [...] }
        rawData = rawData.data
      }

      if (!Array.isArray(rawData)) {
        console.error('Invalid data format received:', typeof rawData, rawData)
        throw new Error('服务器返回的数据格式不正确')
      }

      const transformedData = rawData.map((item, index) => {
        try {
          if (!Array.isArray(item) || item.length < 5) {
            console.warn('Invalid module data at index', index, item)
            return null
          }

          // Map array indices to object properties based on the backend data structure
          return {
            id: item[0] || index.toString(),
            type: item[1] || 'unknown',
            subsystem: item[2] || 'unknown',
            componentName: item[3] || 'unknown',
            name: item[4] || 'Unknown Module',
            modGroup: item[5] || 'unknown',
            // Add more field mappings as needed based on the actual data structure
            deps_total: parseInt(item[7]) || 0,
            deps_indirect: parseInt(item[8]) || 0,
            deps_self: parseInt(item[9]) || 0,
            dependedBy: parseInt(item[10]) || 0,
            // Add any other fields you need
          }
        } catch (err) {
          console.error('Error processing module data at index', index, err)
          return null
        }
      }).filter(Boolean) // Remove null entries

      modules.value = transformedData
      // Handle both direct total field and wrapped response format
      total.value = response.total || (response.data && response.data.total) || modules.value.length

      console.log(`Successfully loaded ${modules.value.length} modules`)
    } catch (error) {
      console.error('Failed to fetch modules:', error)

      // Clear data on error
      modules.value = []
      total.value = 0

      // Re-throw with user-friendly message
      if (error.response?.status === 404) {
        throw new Error('产品或版本不存在，请检查选择是否正确')
      } else if (error.response?.status === 500) {
        throw new Error('服务器内部错误，请稍后重试')
      } else if (error.response?.status >= 500) {
        throw new Error('服务器连接失败，请检查网络连接')
      } else if (error.code === 'NETWORK_ERROR') {
        throw new Error('网络连接失败，请检查网络设置')
      } else {
        throw new Error(error.message || '获取模块数据失败')
      }
    } finally {
      loading.value = false
    }
  }

  const fetchModuleDetail = async (moduleId) => {
    loading.value = true
    try {
      const appStore = useAppStore()
      const productName = appStore.currentProduct
      const version = appStore.currentVersion

      if (!productName) {
        throw new Error('请先选择产品')
      }

      if (!version) {
        throw new Error('请先选择产品版本')
      }

      if (!moduleId) {
        throw new Error('模块ID不能为空')
      }

      const response = await moduleApi.getModuleDetail(moduleId, productName, version)

      if (!response || !response.data) {
        throw new Error('未找到模块详情')
      }

      currentModule.value = response.data
      return currentModule.value
    } catch (error) {
      console.error('Failed to fetch module detail:', error)
      currentModule.value = null

      // Re-throw with user-friendly message
      if (error.response?.status === 404) {
        throw new Error('模块不存在或已被删除')
      } else if (error.response?.status === 500) {
        throw new Error('服务器内部错误，请稍后重试')
      } else {
        throw new Error(error.message || '获取模块详情失败')
      }
    } finally {
      loading.value = false
    }
  }

  const setFilters = (newFilters) => {
    filters.value = { ...filters.value, ...newFilters }
    currentPage.value = 1 // 重置到第一页
  }

  const setCurrentPage = (page) => {
    currentPage.value = page
  }

  const setPageSize = (size) => {
    pageSize.value = size
    currentPage.value = 1
  }

  const clearFilters = () => {
    filters.value = {
      search: '',
      type: '',
      component: '',
      sortBy: 'name',
      sortOrder: 'asc'
    }
    currentPage.value = 1
  }

  const searchModules = async (searchTerm) => {
    filters.value.search = searchTerm
    currentPage.value = 1
  }

  // 导出数据
  const exportModules = async (format = 'json') => {
    try {
      return await moduleApi.exportModules(filters.value, format)
    } catch (error) {
      console.error('Failed to export modules:', error)
      throw error
    }
  }

  return {
    // 状态
    modules,
    currentModule,
    loading,
    total,
    currentPage,
    pageSize,
    filters,

    // 计算属性
    filteredModules,
    paginatedModules,
    moduleStats,

    // 方法
    fetchModules,
    fetchModuleDetail,
    setFilters,
    setCurrentPage,
    setPageSize,
    clearFilters,
    searchModules,
    exportModules
  }
})